//
//  Index_Live_ListViewController.m
//  penzer
//
//  Created by caiyc on 2018/10/1.
//  Copyright © 2018年 caiyc. All rights reserved.
//

#import "Index_Live_ListViewController.h"
#import "Live_Cell.h"
#import "Index_liveCell.h"
#import "Index_LIiveCell.h"
#import "PlayViewController.h"
#import "OYCountDownManager.h"
#import "C_PlayViewController.h"
#import "Regist2ViewController.h"
@interface Index_Live_ListViewController ()<UITableViewDelegate,UITableViewDataSource,UIGestureRecognizerDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property(nonatomic,strong)NSMutableArray *dataSouce;
@property(nonatomic,strong)NSString *now_time;
@property(assign)NSInteger pageIndex;
@property(nonatomic,strong)NSString *key;
@property(nonatomic,strong)NSString *product_cate;
@property(nonatomic,strong)NSString *game_type;
@property(nonatomic,strong)NSString *level;
@property(nonatomic,strong)NSString *age;
@property(nonatomic,strong)NSString *activity_cate;
@property(nonatomic,strong)NSString *sex;
@property(nonatomic,strong)NSString *city;
@property(nonatomic,strong)NSMutableArray *Model_arr;
@property (nonatomic ,strong)dispatch_source_t Dm_timer;
@property(assign)NSInteger times;

#define pagesize 5
@end

@implementation Index_Live_ListViewController
-(NSMutableArray *)Model_arr{
    if(!_Model_arr){
        _Model_arr = [NSMutableArray array];
    }
    return _Model_arr;
}
-(NSMutableArray *)dataSouce{
    if(!_dataSouce){
        _dataSouce=[NSMutableArray array];
        
    }
    return _dataSouce;
}
-(void)viewDidAppear:(BOOL)animated{
    if([XTool GetDefaultInfo:USER_INFO]){
        [self startTime];
    }
}
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [self.parentViewController.view endEditing:1];
   // [self.view endEditing:1];
}
-(void)viewWillAppear:(BOOL)animated{
    
}
-(void)startTime{
    //0.创建队列
    dispatch_queue_t queue = dispatch_get_main_queue();
    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
    //3.要调用的任务
    dispatch_source_set_event_handler(timer, ^{
     //   [self loadStatic];
        self.times++;
        if(self.Model_arr.count>0){
            for(int i =0;i<self.Model_arr.count;i++){
                LiveModel *model = [self.Model_arr objectAtIndex:i];
                if(model.startcount>0){
                    model.startcount--;
                }else{
                    model.startcount=0;
                }
                model.count--;
                if(self.Model_arr.count>0){
                [self.Model_arr replaceObjectAtIndex:i
                                          withObject:model];
                }
            }
            [[NSNotificationCenter defaultCenter] postNotificationName:TimeCellNotification_INDEX object:nil];
        }
    });
    //4.开始执行
    dispatch_resume(timer);
    self.Dm_timer = timer;
}
-(void)stoptime{
    dispatch_cancel(self.Dm_timer);

}
- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(seach:) name:@"search" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(filter:) name:@"filter" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(cityss:) name:@"citys" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(refresh) name:INDEX_SEGECONTREOLL object:nil];
     [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(stoptime) name:STOPTIMENOTO object:nil];
    self.age = @"";
    self.product_cate = @"";
    self.level = @"";
    self.game_type = @"";
    self.activity_cate = @"";
    self.sex = @"";
    self.key = @"";
    self.city = @"";
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.showsVerticalScrollIndicator = 0;
    
    self.tableView.estimatedRowHeight = 0;
    self.tableView.estimatedSectionHeaderHeight = 0;
    self.tableView.estimatedSectionFooterHeight = 0;
    
  //  self.tableView.mj_header  = [MJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(refresh)];
   
   self.tableView.mj_header  = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refresh)];
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self
                                                                    refreshingAction:@selector(loadLiveLis)];
//    NSMutableArray *idleImages = [NSMutableArray array];
//    for (NSUInteger i = 1; i<60; i++) {
//        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"%ld.png", i%16]];
//        [idleImages addObject:image];
//    }
   // NSArray *images = @[@"1.png",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"10",@"11",@"12",@"13",@"14",@"15",@"16"];
    MJRefreshGifHeader *header = [MJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(refresh)];
    // 设置普通状态的动画图片 (idleImages 是图片)
//    [header setImages:idleImages forState:MJRefreshStateIdle];
//    // 设置即将刷新状态的动画图片（一松开就会刷新的状态）
//    [header setImages:idleImages forState:MJRefreshStatePulling];
    // 设置正在刷新状态的动画图片
//    [header setImages:idleImages forState:MJRefreshStateRefreshing];
//    header.lastUpdatedTimeLabel.hidden = 1;
//    header.stateLabel.hidden = 1;
//    // 设置header
//  self.tableView.mj_header = header;

    self.tableView.backgroundColor =viewcontrollerColor;
    [kCountDownManager start];
    self.pageIndex = 1;
    [self loadLiveLis];
//        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(hideKb)];
//        tap.delegate = self;
//        [self.tableView addGestureRecognizer:tap];
  
//    UITapGestureRecognizer *tap= [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(hideKb)];
//    [self.view addGestureRecognizer:tap];
    // Do any additional setup after loading the view from its nib.
}
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch  {
    
    //点击的view的类名
    NSLog(@"%@", NSStringFromClass([touch.view class]));
    
    // UITableViewCellContentView就是点击了tableViewCell，则不截获点击事件
    if ([NSStringFromClass([touch.view class]) isEqualToString:@"UITableView"]){
        
        return NO;
    }
    
    return  YES;
}

-(void)hideKb{
    [self.view endEditing:1];
    [self.parentViewController.view endEditing:1];
}
-(void)cityss:(NSNotification *)no{
      NSDictionary *dic = no.object;
    self.city = [NSString stringWithFormat:@"%@",dic[@"id"]];
    self.pageIndex = 1;
    [self.dataSouce removeAllObjects];
    [self loadLiveLis];
}
-(void)filter:(NSNotification *)no{
    NSDictionary *dic = no.object;
    self.level = dic[@"level"];
    self.age = dic[@"age"];
    self.sex = dic[@"sex"];
    self.product_cate = dic[@"product_cate"];
    self.game_type = dic[@"game"];
    self.pageIndex = 1;
    [self.dataSouce removeAllObjects];
    [self loadLiveLis];
}
-(void)seach:(NSNotification *)no{
    NSString *str = no.object;
    self.key = str;
    self.pageIndex = 1;
    [self.dataSouce removeAllObjects];
    [self loadLiveLis];
}
-(void)refresh{
    [self.dataSouce removeAllObjects];
    [self.Model_arr removeAllObjects];
  //  [kCountDownManager removeAllSource];
    self.pageIndex = 1;
    [self loadLiveLis];
}
-(void)loadCat{
    NSDictionary *param = @{@"ac":@"member",@"op":@"member",@"ctrl":@"live",@"ta":@"category"};
    [self weqPostHandle:param success:^(id response) {
        
    } failure:^(NSError *error) {
        
    }];
}

//获取直播列表
-(void)loadLiveLis{
    if(![XTool GetDefaultInfo:USER_INFO]){
        return;
    }
    NSDictionary *param = @{@"ac":@"store",@"op":@"activity",@"ctrl":@"live",@"product_cate":self.cat_id,@"page":[NSString stringWithFormat:@"%ld",(long)self.pageIndex],@"psize":[NSString stringWithFormat:@"%d",pagesize],@"room_number":self.key,@"product_cate":self.product_cate,@"game_type":self.game_type,@"sex":self.sex,@"age":self.age,@"level":self.level,@"city":self.city};
    [self weqPostHandle:param success:^(id response) {

        if(self.pageIndex == 1){
            [self.tableView.mj_header endRefreshing];
            [self.tableView.mj_footer resetNoMoreData];
        }
        
        if(response){
            
            SLog(@"首页数据输出===%@",response);
            NSArray *acti_Arr = response[@"data"][@"list"];
            if(acti_Arr.count==0){
                [WToast showWithText:@"暂无更多数据"];
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
                
             }else{
                
          //  [self.dataSouce addObjectsFromArray:response[@"data"][@"list"]];
            self.now_time = [NSString stringWithFormat:@"%@",response[@"data"][@"service_time"]];
               
                 NSInteger now_Time = [response[@"data"][@"service_time"]integerValue];
                 for(int i =0;i<acti_Arr.count;i++){
                     NSDictionary *dic = acti_Arr[i];
                     LiveModel *model = [[LiveModel alloc]init];
                     NSInteger counts = [dic[@"end_time"]integerValue]-now_Time;
                     NSInteger starttime =[dic[@"end_time"]integerValue]-now_Time;
                     model.count = counts;
                     model.startcount = [dic[@"start_time"]integerValue]-now_Time;
                     model.timeOut = 0;
                   //  model.countDownSource =  [NSString stringWithFormat:@"OYPagingSource%zd", self.pageIndex];
                     [self.Model_arr addObject:model];
                 }
               
                 [self.dataSouce addObjectsFromArray:response[@"data"][@"list"]];
                 self.now_time = [NSString stringWithFormat:@"%@",response[@"data"][@"service_time"]];
                 [self.tableView.mj_footer endRefreshing];
                 [self.tableView reloadData];
                 self.pageIndex++;
            
            }
           
           
            }else{
            [self.tableView reloadData];
        }
    } failure:^(NSError *error) {
        [self.tableView.mj_header endRefreshing];
         [self.tableView.mj_footer endRefreshing];
        [self.tableView reloadData];
    }];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataSouce.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellId = @"cell";
    Index_liveCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if(!cell)
    {
        cell = [[[NSBundle mainBundle]loadNibNamed:@"Index_liveCell" owner:self options:nil]lastObject];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    NSInteger tiem_New = [self.now_time integerValue]+self.times;
    NSString *time_Str = [NSString stringWithFormat:@"%ld",tiem_New];
    cell.model = self.Model_arr[indexPath.row];
    [cell bindData:self.dataSouce[indexPath.row] andtime:time_Str];
    __weak typeof (self)weakSelf = self;
    cell.countDownZero=^(LiveModel * model){
//        LiveModel *models = self.Model_arr[indexPath.row];
         LiveModel *models = model;
        if(models.startcount>0){
            //未开始的状态
            models.count = models.count-models.startcount;
            models.startcount = 0;
            NSLog(@"开始的倒计时结束");
        }else{
            //直播结束
            
            models.count=0;
            models.timeOut = 1;
            NSLog(@"直播倒计时结束");
        }
        model.countDownSource =  [NSString stringWithFormat:@"OYPagingSource%zd", self.pageIndex];
        [self.Model_arr replaceObjectAtIndex:indexPath.row withObject:models];
         [weakSelf.tableView reloadData];
//        NSIndexPath *index = [NSIndexPath indexPathForRow:indexPath.row inSection:0];
//        [weakSelf.tableView reloadRowsAtIndexPaths:@[index] withRowAnimation:UITableViewRowAnimationRight];
      //  [kCountDownManager reload];
    };
    return cell;

}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 186;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary *dic = [self.dataSouce objectAtIndex:indexPath.row];
    [self enterRoom:dic];
   
}
-(void)enterRoom:(NSDictionary *)dic{
   // Regist2ViewController *vc = [[Regist2ViewController alloc]init];
  
    NSString *live_Id = [NSString stringWithFormat:@"%@",dic[@"activityid"]];
    NSString *roomNum = [NSString stringWithFormat:@"%@",dic[@"room_number"]];
    NSDictionary *paramter = @{@"op":@"address",@"ctrl":@"live",@"ac":@"member",@"ta":@"check_actroom_address",@"aid":live_Id};
    [self weqPostHandle:paramter success:^(id response) {
        if(response){
            C_PlayViewController *vc = [[C_PlayViewController alloc]init];
            vc.live_id = live_Id;
            vc.roomNum= roomNum;
           [self pushSecondVC:vc];
        }else{
            Regist2ViewController *vc = [[Regist2ViewController alloc]init];
            vc.live_id = live_Id;
            vc.roomNum = roomNum;
            [self pushSecondVC:vc];
        }
    } failure:^(NSError *error) {
        
    }];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/


@end
